<?php

namespace app\sys\controller;

use think\Db;

// 后台 提现管理
class Withdraw extends Admin
{
    // 提现记录
    public function index()
    {
        $admin_info = session('admin_info');
        $date = input('param.date', '');
        $page = input('param.page', 1);
        $page = $page <= 0 ? 1 : $page;
        $limit = input('param.limit', 20);
        $order_field = input('param.field', '');
        $order_type = input('param.order', 0);
        if (request()->isAjax()) {
            $status = config('withdraw_status');
            $query = [];
            if ($admin_info['permission'] !=10) {
                $query['admin_id'] = $admin_info['id'];
            }
            if ($date) {
                $arr = explode('~', $date);
                $query['ct'] = [['gte', strtotime(trim($arr[0]))], ['lte', strtotime(trim($arr[1]).'23:59:59')]];
            }
            $order = ['ct' => -1];
            if ($order_field && $order_type) {
                $order[$order_field] = 'asc' == $order_type ? 1 : -1;
            }
            $list = Db::name('withdraw')->where($query)->page($page)->limit($limit)->order($order)->select();
            foreach ($list as $key => $value) {
                $find = Db::name('admin')->find($value['admin_id']);
                $list[$key]['name'] = $find['username'];
                $list[$key]['ct'] = date('Y-m-d H:i:s', $value['ct']);
                $list[$key]['handle_time'] = date('Y-m-d H:i:s', $value['handle_time']);
                $list[$key]['status'] = $status[$value['status']];
            }
            $count = Db::name('withdraw')->where($query)->count();

            return success(['data' => $list, 'count' => $count]);
        }

        return view('index');
    }

    // 提现
    public function withdraw()
    {
        $admin_info = session('admin_info');
        $admin_db_info = Db::name('admin')->find($admin_info['id']);
        if (request()->isPost()) {
            if (!$admin_db_info['openid']) {
                return error('请先绑定微信');
            }
            $money = input('param.money', 1);
            $money = round($money, 2);
            if ($money < 1) {
                return error('单次提现金额不能小于1元！');
            }
            if ($money > 20000) {
                return error('为了您的支付安全单次提现金额不能大于2万');
            }
            if ($admin_info['permission'] < 6) {
                return error('您的权限不够');
            }

            if ($admin_db_info['balance'] < $money) {
                return error('提现金额不能大于账户余额');
            }
            $row = ['admin_id' => $admin_db_info['id'], 'money' => $money, 'status' => 0, 'openid' => $admin_db_info['openid'], 'ct' => time()];
            Db::name('admin')->where('id', $admin_info['id'])->update(['balance' => round($admin_db_info['balance'] - $money, 2)]);
            Db::name('withdraw')->insert($row);

            return success();
        }

        return view('withdraw', ['admin_info' => $admin_db_info]);
    }

    // 支付
    public function pay()
    {
        if (request()->isPost()) {
            $id = input('param.id', '');

            $admin_info = session('admin_info');
            if (10 != $admin_info['permission']) {
                return error('您的权限不够');
            }
            $info = Db::name('withdraw')->find($id);
            if (!$info) {
                return error('未找到该提现申请');
            }
            if (!$info['openid']) {
                return error('数据错误：缺少的openid');
            }
            $info['money'] = round($info['money'], 2);

            if ($info['money'] < 1) {
                return error('单次提现金额不能小于1元！');
            }
            if ($info['money'] > 20000) {
                return error('单次提现金额不能大于2万');
            }
            // 微信自动支付
            $wx_service = new \wx\WeixinService();
            $row = ['id' => $info['id'], 'openid' => $info['openid'], 'desc' => '提现', 'pay_money' => $info['money']];
            $result = $wx_service->serverAutoPay($row);
            if ('SUCCESS' == $result['return_code'] && 'SUCCESS' == $result['result_code']) {
                Db::name('withdraw')->where('id', $result['partner_trade_no'])->update(['status' => 1, 'handle_time' => time(), 'pay_time' => time(), 'payment_no' => $result['payment_no']]);
                $find_admin = Db::name('admin')->where('id', $info['admin_id'])->find();
                Db::name('admin')->where('id', $info['admin_id'])->update(['withdraw' => round($find_admin['withdraw'] + $info['money'], 2)]);

                return success($result);
            }

            return error($result);
        }

        return error();
    }

    // 删除
    public function del()
    {
        if (request()->isPost()) {
            $id = input('param.id', '');
            $admin_info = session('admin_info');
            if (10 != $admin_info['permission']) {
                return error('您的权限不够');
            }
            $withdraw = Db::name('withdraw')->find($id);
            $admin_db_info = Db::name('admin')->find($withdraw['admin_id']);
            Db::name('admin')->where('id', $withdraw['admin_id'])->update(['balance' => round($admin_db_info['balance'] + $withdraw['money'], 2)]);
            Db::name('withdraw')->delete($id);

            return success();
        }

        return error();
    }

    // 驳回
    public function reject()
    {
        if (request()->isPost()) {
            $id = input('param.id', '');
            $remark = input('param.remark', '');
            $admin_info = session('admin_info');
            if (10 != $admin_info['permission']) {
                return error('您的权限不够');
            }
            $withdraw = Db::name('withdraw')->find($id);
            $admin_db_info = Db::name('admin')->find($withdraw['admin_id']);
            Db::name('admin')->where('id', $withdraw['admin_id'])->update(['balance' => round($admin_db_info['balance'] + $withdraw['money'], 2)]);
            $update_row = ['status' => 2, 'handle_time' => time()];
            if ($remark) {
                $update_row['remark'] = $remark;
            }
            Db::name('withdraw')->where(['id' => $id])->update($update_row);

            return success();
        }

        return error();
    }

    // 发送验证码
    public function sendVerificationCode()
    {
        if (request()->isPost()) {
            $admin_info = session('admin_info');
            $phone = $admin_info['phone'];
            // 对同一个手机号， 30秒 内发送短信条数不超过 1条 对同一个手机号， 1小时 内发送短信条数不超过 5条 对同一个手机号， 1个自然日 内发送短信条数不超过 10条
            // 缓存5分钟
            $get_cache = cache('verification_code_phone_'.$phone);
            if ($get_cache) {
                return error('验证码已经发送，请查看手机短信');
            }
            $code = mt_rand(1000, 9999);
            $res = sendVerificationCode($phone, $code);
            if (0 == $res['result']) {
                cache('verification_code_phone_'.$phone, $code, 300);

                return success('验证码发送成功');
            } else {
                return error('验证码发送失败');
            }
        }

        return error();
    }

    // 绑定手机号
    public function bindPhone()
    {
        if (request()->isPost()) {
            $admin_info = session('admin_info');
            $phone = $admin_info['phone'];
            $code = input('post.code', '');
            if (!$code) {
                return error('请填写验证码');
            }
            $server_code = cache('verification_code_phone_'.$phone);
            if ($server_code == $code) {
                $admin_info = session('admin_info');
                Db::name('admin')->where('id', $admin_info['id'])->update(['bind_phone' => 1]);

                return success('绑定成功');
            } else {
                return error('验证码错误');
            }
        }

        return error();
    }
}
